<template>
    <Card style="min-height: 500px;height: 90vh">
        <Form ref="searchData" :model="searchData" :rules="ruleInline" label-colon autocomplete="off" style="margin-top: 20px" >
          <permission-button-group only-add @handleEvent="handleEvent" :show-add="showAdd" permission-code-prefix="organization_" fullscreen-able/>
        </Form>
      <vue2-org-tree :data="resultData" :props="props" collapsable labelClassName="custom-org-node" @on-expand="onExpand" :renderContent ="nodeRender2"/>
        <organization-detail :show-modal="showModal" :can-edit="canEdit" :organization-data="modalData" :title="modalTitle"
                             @callbackByCancel="callbackByCancel" @callbackByOk="callbackByOk"/>
    </Card>
</template>
<script>
import {deleteData, search} from '@/api/organizationApi'
import OrganizationDataProvider from '@/views/group_management/data/OrganizationDataProvider'
import OrganizationDetail from '@/views/group_management/organization/components/organization-detail'
import PermissionButtonGroup from '@/components/permissionButton/permission-button-group'
import PermissionService from "../../../service/PermissionService";

const menuList = [
  {
    key: 'edit',
    label: '编辑部门'
  },
  {
    key: 'view',
    label: '查看部门'
  },
  {
    key: 'add',
    label: '新增子部门'
  },
  {
    key: 'delete',
    label: '删除部门'
  }
]
export default {
  components: {
    OrganizationDetail,
    PermissionButtonGroup
  },
  data() {
    return {
      showModal: false,
      canEdit: true,
      showAdd: false,
      searchData: {
        comCode: '',
        comName: ''
      },
      zoom:1,
      orgTreeOffsetLeft: 0,
      orgTreeOffsetTop: 0,
      props:{label: 'comName', children: 'children', expand: 'expand'},
      modalTitle: '添加组织机构',
      modalData: OrganizationDataProvider.createOrganizationVo(),
      selectItem: null,
      operateData:{},
      ruleInline: {},
      upperComCode: '',
      resultData: {},
      buttonPermissions:[]
    }
  },
  created() {

  },
  mounted() {
    PermissionService.getButtonPermissions().then(res=> {
      this.buttonPermissions = res
      this.queryData()
        }
    );
  },
  computed: {
    orgTreeStyle () {
      return {
        transform: `translate(-50%, -50%) scale(${this.zoom}, ${
            this.zoom
        })`,
      }
    }
  },
  methods: {
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    queryData() {
      search(this.searchData).then(res => {
        if (Array.isArray(res)){
          this.showAdd = res[0].length>0
          this.resultData = res[0]
          this.toggleExpand(this.resultData,true)
        }

      })
    },
    callbackByCancel() {
      this.showModal = false
    },
    callbackByOk() {
      this.showModal = false
      this.queryData()
    },
    handleEvent(event) {
      if(event==='organization_add'){
        this.modalTitle = '添加组织机构'
        this.canEdit = true
        this.modalData = OrganizationDataProvider.createOrganizationVo()
        this.showModal = true
      }
      else if (event === 'add') {
        this.modalTitle = '添加组织机构'
        this.canEdit = true
        this.modalData = OrganizationDataProvider.createOrganizationVo()
        this.modalData.upperComCode = this.operateData.comCode
        this.showModal = true
      } else {
        if (event === 'view' || event === 'edit') {
          this.canEdit = event !== 'view'
          this.modalTitle = '组织机构'
          this.modalData = this.operateData
          this.showModal = true
        }
        if (event === 'delete') {
          this.$Modal.confirm({
            title: '删除部门确认',
            content: '是否要删除【'+this.operateData.comName+'】',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              let selectDataId = []
              selectDataId.push(this.operateData.comCode)
              deleteData(selectDataId).then(() => {
                this.$Message.success('删除成功！')
                this.queryData()
              })
            },
            onCancel:()=>{
              console.log('取消')
            }
          });

        }
      }
    },
    collapse(list) {
      list.forEach((child)=> {
        if (child.expand) {
          child.expand = false;
        }
        child.children && this.collapse(child.children);
      });
    },
    onExpand(e,data) {
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, "expand", true);
      }
    },
    toggleExpand(data, val) {
      if (Array.isArray(data)) {
        data.forEach((item)=> {
          this.$set(item, "expand", val);
          if (item.children) {
            this.toggleExpand(item.children, val);
          }
        });
      } else {
        this.$set(data, "expand", val);
        if (data.children) {
          this.toggleExpand(data.children, val);
        }
      }
    },
    nodeRender2(h,data){
      let menuItems = [];
      menuList.map(item => {
        if (this.buttonPermissions.includes('organization_'+item.key)){
          menuItems.push(h('DropdownItem',{
            props:{name:item.key}
          },item.label))
        }
      })
      return h("Dropdown", {
        props: {
          trigger: 'contextMenu',
        },
        on:{
          'on-click':(event)=>{
            this.itemClick(event,data)
          }
        }
      }, [
        h("div",{style:{
            padding: '10px',
          },},data.comName),
        h("DropdownMenu", {
          slot: "list"
        },menuItems)
      ])
    },
    itemClick(event,data){
      this.operateData = data
      this.handleEvent(event)
    },
  }
}
</script>
<style>
.org-tree-node-label-inner {
   padding: 0 !important;
}
.custom-org-node {
  background: #738699;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  white-space: nowrap;
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
  -webkit-transition: background .1s ease-in;
  transition: background .1s ease-in;
  cursor: default;
}
</style>